Day28 要來做個影片速度的控制器
const VIDEO_URL =
"https://github.com/wesbos/JavaScript30/raw/master/11%20-%20Custom%20Video%20Player/652333414.mp4";
const [playbackRate, setPlaybackRate] = useState<number>(1);
const videoRef = useRef<HTMLVideoElement>(null);
const speedBarRef = useRef<HTMLDivElement>(null);
const handleSpeedChange = (e: MouseEvent<HTMLDivElement>) => {
const speedBar = speedBarRef.current;
const video = videoRef.current;
if (!speedBar || !video) {
return;
}
const y = e.nativeEvent.offsetY;
const percent = y / speedBar.offsetHeight;
const min = 0.4;
const max = 4;
const newPlaybackRate = percent * (max - min) + min;
setPlaybackRate(newPlaybackRate);
video.playbackRate = newPlaybackRate;
};
return (
<div className="flex items-center justify-center h-screen bg-gray-100">
<div className="relative">
<video
className="rounded-lg shadow-lg"
width="765"
height="430"
src={VIDEO_URL}
ref={videoRef}
controls
></video>
<div
className="absolute top-0 right-0 h-full w-10 bg-gray-200 cursor-pointer"
ref={speedBarRef}
onClick={handleSpeedChange}
>
<div
className="relative h-full w-full bg-yellow-400 flex items-center justify-center"
style={{ height: `${((playbackRate - 0.4) / 3.6) * 100}%` }}
>
<span className="speed-bar text-xs font-bold text-gray-800">
{playbackRate.toFixed(2)}x
</span>
</div>
</div>
</div>
</div>
);